package com.seek.service.imp;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.seek.core.BaseServiceImpl;
import com.seek.dao.CompanyAgentMoneyDao;
import com.seek.model.entity.TCompanyAgentMoney;
import com.seek.service.CompanyAgentMoneyService;
import com.seek.util.CommonUtil;

@Repository("companyAgentMoneyService")
public class CompanyAgentMoneyServiceImpl extends BaseServiceImpl<TCompanyAgentMoney>
		implements CompanyAgentMoneyService {

	@Autowired
	public void setDao(CompanyAgentMoneyDao companyAgentMoneyDao) {
		super.setDao(companyAgentMoneyDao);
	}

	public CompanyAgentMoneyDao getDao() {
		return (CompanyAgentMoneyDao) super.getDao();
	}

	@SuppressWarnings("unchecked")
	public int[] getAgentMoneySetting(Long agentId, Long subAgentId, int moneyType) throws Exception {
		int[] money = new int[2];
		StringBuffer sb = new StringBuffer("");
		sb.append("select '1' type, a.money").append(" from t_company_agent a where a.id=? and a.money_type=?")
				.append(" union all").append(" select '2' type, a.money")
				.append(" from t_company_agent a where a.id=? and a.money_type=?");
		List<Map<String, Object>> ds = this.getDao().findMapBySql(sb.toString(), new Object[] { agentId, moneyType,subAgentId,moneyType });
		if (ds == null || ds.size() < 1) {
			return money;
		}

		for (Map<String, Object> en : ds) {
			if ("1".equals(en.get("type"))) {
				money[0] = CommonUtil.getIntValue(en.get("money"));
			}
			if ("2".equals(en.get("type"))) {
				money[1] = CommonUtil.getIntValue(en.get("money"));
			}
		}

		money[0] = money[0] - money[1];
		return money;
	}
	
	public void addAgentMoneyLog(Long agentId, Long subAgentId, int agentMoney, int subAgentMoney, Long loanId,Long custId,int moneyType) throws Exception{
		// 添加一级代理商佣金记录
		String sql = "insert into t_company_agent_money(agent_id,loan_id,customer_id,money_type,create_time,money,sub_agent_id,sub_agent_money) select ?,?,?,?,now(),?,?,?";
		this.getDao().executeUpdateSql(sql, new Object[] { agentId, loanId, custId, moneyType, agentMoney, subAgentId, subAgentMoney });
		if (subAgentId != null && subAgentId.longValue()>0) {
			sql = "insert into t_company_agent_money(agent_id,loan_id,customer_id,money_type,create_time,money) select ?,?,?,?,now(),?";
			this.getDao().executeUpdateSql(sql, new Object[] { subAgentId, loanId, custId, moneyType, subAgentMoney });
		}
	}
}